package com.jyh.blog.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyh.blog.dao.PageDao;
import com.jyh.blog.entity.Page;
import com.jyh.blog.service.PageService;
import com.jyh.blog.service.RedisService;
import com.jyh.blog.utils.BeanCopyUtils;
import com.jyh.blog.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

import static com.jyh.blog.constant.RedisPrefixConst.PAGE_COVER;

/**
 * 页面(Page)表服务实现类
 *
 * @author jyh
 * @since 2023-03-06 20:20:23
 */
@Service("pageService")
public class PageServiceImpl extends ServiceImpl<PageDao, Page> implements PageService {
    @Autowired
    private RedisService redisService;

    @Override
    public List<PageVO> pageList() {
        List<PageVO> pageVOList;
        //从redis中获取，没有才从mysql中查
        Object list = redisService.get(PAGE_COVER);
        //缓存不为空
        if(Objects.nonNull(list)){
            pageVOList = JSON.parseObject(list.toString(), List.class);
        }else {
            //查询mysql,将查询结果(list)封装为pageVO放入缓存
            pageVOList = BeanCopyUtils.copyList(this.list(), PageVO.class);
            redisService.set(PAGE_COVER, JSON.toJSONString(pageVOList));
        }
        return pageVOList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdatePage(PageVO pageVO) {
        Page page = BeanCopyUtils.copyObject(pageVO, Page.class);
        this.saveOrUpdate(page);
        //清除缓存
        redisService.del(PAGE_COVER);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deletePageById(Integer id) {
        this.removeById(id);
        //清除缓存
        redisService.del(PAGE_COVER);
    }
}

